/**
 * $version:  0.1 
 * $Date: 2012-04-05 
 *
 * Copyright (C) 2010-2012 Jawa Software. All rights reserved.
 *
 */

package org.jawa.start;

import java.io.File;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * 一个简单的ClassLoader来扩展类路径中包括一个lib目录中的所有JAR包
 * 新的类路径中包含所有<tt>*.jar</tt> 和 <tt>*.zip</tt>的文件(zip文件通常用于数据库驱动)
 * 扩展的路径用于插件加载时的支持和最初的服务器启动
 * 该类负责装载jawa安装目录下面lib目录下的库或者资源
 *
 * @author wangyougui
 */
class JawaClassLoader extends URLClassLoader {

    /**
     * 构造函数.
     *
     * @param parent the parent class loader (or null for none).
     * @param libDir the directory to load jar files from.
     * @throws java.net.MalformedURLException if the libDir path is not valid.
     */
    JawaClassLoader(ClassLoader parent, File libDir) throws MalformedURLException {
        super(new URL[] { libDir.toURI().toURL() }, parent);

        File[] jars = libDir.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                boolean accept = false;
                String smallName = name.toLowerCase();
                if (smallName.endsWith(".jar")) {
                    accept = true;
                }
                else if (smallName.endsWith(".zip")) {
                    accept = true;
                }
                return accept;
            }
        });

        // Do nothing if no jar or zip files were found
        if (jars == null) {
            return;
        }

        for (int i = 0; i < jars.length; i++) {
            if (jars[i].isFile()) {
                addURL(jars[i].toURI().toURL());
            }
        }
    }
}
